package com.yc.cloud.openai.portal.task;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.yc.cloud.common.oss.entity.OssFile;
import com.yc.cloud.common.oss.service.OssFileService;
import com.yc.cloud.openai.entity.ModelRecord;
import com.yc.cloud.openai.portal.dao.ModelClient;
import com.yc.cloud.openai.portal.enums.ModelProvider;
import com.yc.cloud.openai.portal.enums.PrompOutputType;
import com.yc.cloud.openai.portal.enums.TaskStatusEnums;
import com.yc.cloud.openai.portal.factory.ModelClientFactory;
import com.yc.cloud.openai.portal.service.ModelRecordService;
import com.yc.cloud.openai.portal.vo.HistoryVo;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import lombok.val;
import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
// @ConditionalOnProperty(name = "spring.profiles.active", havingValue = "dev")
public class ModelRecordTask {
    private final Map<ModelProvider, ModelClient> modelClientMap;
    private final ModelRecordService modelRecordService;
    private List<String> statusList;
    private final OssFileService ossFileService;

    public ModelRecordTask(ModelClientFactory modelClientFactory,
            ModelRecordService modelRecordService,
            OssFileService ossFileService) {
        this.modelRecordService = modelRecordService;
        this.modelClientMap = modelClientFactory.getClientMap();
        this.ossFileService = ossFileService;
        initStatusList();
    }

    @Scheduled(fixedDelay = 10L, timeUnit = TimeUnit.SECONDS)
    // 同步视频AI生成的记录状态
    public void syncModelRecordStatus() {
        val modelRecordList = modelRecordService.listByStatus(statusList);
        if (CollUtil.isEmpty(modelRecordList)) {
            return;
        }
        for (val modelRecord : modelRecordList) {
            val provider = modelRecord.getProvider();
            val uuid = modelRecord.getUuid();
            if (StrUtil.isEmpty(provider)) {
                log.error("未知的模型AI提供商 任务ID:{}", modelRecord.getUuid());
                continue;
            }
            // 类型生成方式类型
            val modelClient = modelClientMap.get(ModelProvider.fromKey(provider));
            if (modelClient == null) {
                log.error("未知的图片转3D模型AI提供商 :{}", modelRecord.getProvider());
                continue;
            }
            val modelHistory = getModelHistory(modelClient, modelRecord);
            if (CollUtil.isEmpty(modelHistory)) {
                continue;
            }
            val ossFileList = new ArrayList<OssFile>();
            for (val model : modelHistory) {
                val path = model.getPath();
                if (FileUtil.exist(path)) {
                    modelRecord.setStatus(TaskStatusEnums.FINISHED.getKey());
                    val updateFlag = modelRecordService.updateById(modelRecord);
                    if (updateFlag) {
                        val fileId = ossFileService.generateFileId();
                        val ossFile = ossFileService.buildOssFile(fileId, model.getName(), path);
                        // 使用任务ID作为他的父级文件ID做关联
                        ossFile.setParentFileId(uuid);
                        ossFileList.add(ossFile);
                    }
                }
            }
            if (CollUtil.isEmpty(ossFileList)) {
                continue;
            }
            ossFileService.saveBatch(ossFileList);
        }
    }

    /**
     * 获取AI生成的模型历史记录
     *
     * @param textToVideoClient 视频AI客户端
     * @param provider          视频AI提供商
     * @param promptId          视频AI任务ID
     * @return 视频AI生成的历史记录
     */
    private List<HistoryVo> getModelHistory(ModelClient modelClient, ModelRecord modelRecord) {
        val historyResponse = modelClient.history(modelRecord.getUuid(), modelRecord.getType());
        if (historyResponse != null && CollUtil.isNotEmpty(historyResponse.getHistoryList())) {
            return historyResponse.getHistoryList();

        }
        return null;
    }

    private void initStatusList() {
        statusList = new ArrayList<>();
        statusList.add(TaskStatusEnums.PENDING.getKey());
        statusList.add(TaskStatusEnums.PROGRESS.getKey());
    }
}
